import { call, put, fork, select, take } from 'redux-saga/effects'
import { message } from 'antd'
import actions,{ ADD, GET_INDUSTRY_ENUM, GET_SCENARIOS_ENUM } from '@/actions/signEdit'
import api from '@/api/signEdit'
import enumApi from '@/api/enum'
import { history } from '@/route/history'
import successDesc from '@/constants/success'

function* add() {
  try {
    const params = yield select(({ signEditReducer: { sign, industry, scenarios } }) => ({
      sign,
      industry,
      application: scenarios
    }))
    const { isSuccess, desc } = yield call(api.addSign, params)
    if(isSuccess) {
      yield put(actions.addSuccess())
      message.success(successDesc.add)
      history.push('/index/sign')
    }else {
      throw new Error(desc)
    }
  } catch (error) {
    yield put(actions.addFail())
    message.error(error.message || '添加错误')
  }
}

function* watchAdd() {
  while (true) {
    yield take(ADD)
    yield call(add)
  }
}

function* getIndustryEnum() {
  try {
    const { isSuccess, data } = yield call(enumApi.getIndustryEnum)
    if(isSuccess && Array.isArray(data)){
      yield put(actions.getIndustryEnumSuccess(data))
      if(data.length) yield put(actions.setIndustry(data[0].index + ''))
    }
  } catch (error) {
    
  }
}

function* getScenariosEnum() {
  try {
    const { isSuccess, data } = yield call(enumApi.getScenariosEnum)
    if(isSuccess){
      yield put(actions.getScenariosEnumSuccess(data))
      if(data.length) yield put(actions.setScenarios(data[0].index + ''))
    }
  } catch (error) {
    
  }
}

function* watchGetIndustryEnum() {
  while (true) {
    yield take(GET_INDUSTRY_ENUM)
    yield call(getIndustryEnum)
  }
}

function* watchGetScenariosEnum() {
  while (true) {
    yield take(GET_SCENARIOS_ENUM)
    yield call(getScenariosEnum)
  }
}

export default [
  fork(watchAdd),
  fork(watchGetIndustryEnum),
  fork(watchGetScenariosEnum)
]